package com.jingxuan.controller;

import com.jingxuan.common.annotation.NoAuth;
import com.jingxuan.common.result.Result;
import com.jingxuan.dto.request.UserLoginRequest;
import com.jingxuan.dto.response.LoginResponse;
import com.jingxuan.interceptor.AuthInterceptor;
import com.jingxuan.service.AuthService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 */
import com.jingxuan.service.RankService;
import java.util.concurrent.CompletableFuture;

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private RankService rankService;

    /**
     * 用户登录
     * POST /api/auth/login
     */
    @NoAuth
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody UserLoginRequest request) {
        log.info("用户登录请求，phone: {}", request.getPhone());
        LoginResponse response = authService.login(request);

        return Result.success("登录成功", response);
    }

    /**
     * 用户登出
     * POST /api/auth/logout
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        Long userId = AuthInterceptor.getCurrentUserId();
        log.info("用户登出请求，userId: {}", userId);
        authService.logout(userId);

        // 清空排行榜缓存
        try {
            rankService.clearAllRankings();
        } catch (Exception e) {
            log.error("清空排行榜缓存失败", e);
        }

        return Result.success("登出成功", null);
    }
}
